home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: ?Help - struct array of strings
- Date: 11 Mar 1996 13:56:33 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4i27ihINN333@keats.ugrad.cs.ubc.ca>
- References: <4hvpgp$gu7@ftp.netgate.net>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <4hvpgp$gu7@ftp.netgate.net>,
- Tamara Johnson <malihini@netgate.net> wrote:
- >/*
- > program to enter author(s), title(s)
- > then display entries.
- > why is printf displaying strange things?
- > (see output at end)
- >*/
- >
- >#include <stdlib.h>
- >#include <stdio.h>
- >#include <conio.h>
- >#include <string.h>
- >
- >#define MAX 5
-
- MAX is 5.
-
- >struct catalog{
- > char name[80]; /* author name */
- > char title[80]; /* title */
- >}cat[80];
-
- But array has 80 things? Why not cat[MAX]?
-
- >void main()
- ^^^^
-
- Bad! You are not free to give main() any old return type. The required type is
- int.
-
- >{
- >int i;
- >
- >for(i=0;i<MAX;i++)
- > {
- > printf("Enter author name (ENTER to quit); ");
- > gets(cat[i].name);
-
- The gets function is "bad". The user could type more than the available buffers
- space. But you can get away with it here, I suppose.
-
- > if(!*cat[i].name) break;
- > printf("Enter title: ");
- > gets(cat[i].title);
- > }
- >for(i=0;i<MAX;i++)
-
- The user could have entered fewer than MAX record. Break out of the loop as you
- did above.
-
- > printf("%c %c\n", cat[i].name, cat[i].title);
-
- The %c conversion specifier calls for a char type. You are giving it a pointer
- to char. The pointers are being interpreted as characters, yielding undefined
- behavior. You want the %s specifier.
-
- If you really want to print just the first character of each name and title,
- you must do it like this:
-
- printf("%c %c\n", *cat[i].name, cat[i].title[0]);
-
- Both methods produce the first character; the first is what you used in your
- input loop to check for the first character being a zero.
-
- There should be a return value here. Main is a function returning int, and
- requires a return value, otherwise the exit status of the program is undefined:
-
- return 0;
-
- >}
- --
-
-